﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ParsecParser;
using ParsecParser.Communication;
using ParsecParser.Data;
using ParsecParser.Display;
using ParsecParser.Helpers;
using ParsecClient.Classes;
using Microsoft.Win32;

namespace ParsecClient
{
    /// <summary>
    /// Interaction logic for ManageTimers.xaml
    /// </summary>
    public partial class ManageTimers : Window
    {
        private string LastOpenedSoundFolder;
        public ManageTimers()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var tds = ((App)Application.Current).GetTimerDefinitions();
                var timers = tds.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                lstTimers.ItemsSource = timers;
                lstTimers.SelectedValuePath = "Content";
                cmbTriggerTimerName.ItemsSource = timers;
                cmbTriggerTimerName.SelectedValuePath = "Content";
                cmbTriggerTimerName.DisplayMemberPath = "Content";
                cmbCancelTimerName.ItemsSource = timers;
                cmbCancelTimerName.SelectedValuePath = "Content";
                cmbCancelTimerName.DisplayMemberPath = "Content";
                cmbCategory.ItemsSource = tds.Where(x => !string.IsNullOrEmpty(x.Category)).Select(x => x.Category).Distinct().OrderBy(x => x).Select(x => new ListBoxItem() { Content = x }).ToList();
                cmbCategory.SelectedValuePath = "Content";
                cmbCategory.DisplayMemberPath = "Content";
                ddlTrigger.ItemsSource = TimerDefinition.TimerTrigerValues;
                ddlTrigger.SelectedValuePath = "Key";
                ddlTrigger.DisplayMemberPath = "Value";
                ddlTriggerType.ItemsSource = TimerDefinition.TimerTrigerTypeValues;
                ddlTriggerType.SelectedValuePath = "Key";
                ddlTriggerType.DisplayMemberPath = "Value";
                ddlTriggerTarget.ItemsSource = TimerDefinition.TimerTriggerTargetValues;
                ddlTriggerTarget.SelectedValuePath = "Key";
                ddlTriggerTarget.DisplayMemberPath = "Value";
                ddlTriggerTargetName.ItemsSource = TimerDefinition.TimerTriggerTargetNameValues;
                ddlTriggerTargetName.SelectedValuePath = "Key";
                ddlTriggerTargetName.DisplayMemberPath = "Value";
                ddlMultiTimerMode.ItemsSource = TimerDefinition.MultipleTimerModeValues;
                ddlMultiTimerMode.SelectedValuePath = "Key";
                ddlMultiTimerMode.DisplayMemberPath = "Value";
                ddlSoundEffect.ItemsSource = Enum.GetValues(typeof(TimerSound)).Cast<TimerSound>().Select(x => new { Value = x, Display = Enum.GetName(typeof(TimerSound), x).GetPascalCaseAsWords() }).OrderBy(x => x.Value == TimerSound.None ? 0 : x.Value == TimerSound.Custom || x.Value == TimerSound.TextToSpeech ? 2 : 1).ThenBy(x => x.Display).ToList();
                ddlSoundEffect.SelectedValuePath = "Value";
                ddlSoundEffect.DisplayMemberPath = "Display";
                grdFields.Visibility = System.Windows.Visibility.Hidden;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on Window_Loaded", ex, this, true);
            }
        }

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ConfirmUnsaved())
                {
                    if (string.IsNullOrEmpty(txtNewTimerName.Text.Trim()))
                    {
                        ((App)Application.Current).HandleError("You must provide a Timer Name", null, null, this, false);
                    }
                    else
                    {
                        var timerDefs = ((App)Application.Current).GetTimerDefinitions();
                        if (timerDefs.Count(x => string.Compare(x.Description, txtNewTimerName.Text.Trim(), true) == 0) != 0)
                        {
                            ((App)Application.Current).HandleError("Timer Name Already Exists", null, null, this, false);
                        }
                        else
                        {
                            ((App)Application.Current).AddTimerDefinition(new TimerDefinition(txtNewTimerName.Text.Trim(), TimerTrigger.YouActivateAnAbility, null, 0, 0, TimerSound.ItsATrap, MultipleTimerMode.AllowMultipleTimers));
                            timerDefs = ((App)Application.Current).GetTimerDefinitions();
                            var timers = timerDefs.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                            lstTimers.ItemsSource = timers;
                            lstTimers.SelectedValuePath = "Content";
                            lstTimers.SelectedValue = txtNewTimerName.Text.Trim();
                            cmbTriggerTimerName.ItemsSource = timers;
                            cmbTriggerTimerName.SelectedValuePath = "Content";
                            cmbTriggerTimerName.DisplayMemberPath = "Content";
                            cmbCancelTimerName.ItemsSource = timers;
                            cmbCancelTimerName.SelectedValuePath = "Content";
                            cmbCancelTimerName.DisplayMemberPath = "Content";
                            BindTimerForm();
                            txtNewTimerName.Text = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCreate_Click", ex, this, true);
            }
        }

        private void btnCancelTimer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                lblUnsaved.Visibility = System.Windows.Visibility.Collapsed;
                lstTimers.SelectedValue = null;
                BindTimerForm();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCancelTimer_Click", ex, this, true);
            }
        }

        private void btnSaveTimer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //if selected value doesnt equal current name then verify if name change is ok
                bool nameChanged = false;
                var tdefs = ((App)Application.Current).GetTimerDefinitions();
                if (string.Compare((string)lstTimers.SelectedValue, txtTimerName.Text.Trim(), false) != 0)
                {
                    if (tdefs.Count(x => string.Compare(x.Description, txtTimerName.Text.Trim(), true) == 0) != 0)
                    {
                        ((App)Application.Current).HandleError("Timer Name Already Exists", null, null, this, false);
                        return;
                    }
                    nameChanged = true;
                }
                double interval = 0;
                int repeatCount = 0;
                if (!int.TryParse(txtRepeatCount.Text, out repeatCount) || repeatCount < 0 || repeatCount > 99)
                {
                    ((App)Application.Current).HandleError("Repeat Count must be an integer between 0 - 99", null, null, this, false);
                    return;
                }
                if (!double.TryParse(txtInterval.Text, out interval) || interval < 0 || interval > 1200)
                {
                    ((App)Application.Current).HandleError("Interval Seconds must be valid decimal between 0 - 1200", null, null, this, false);
                    return;
                }
                if (((TimerSound)ddlSoundEffect.SelectedValue) == TimerSound.Custom)
                {
                    if (string.IsNullOrEmpty(txtCustomSound.Text) || !System.IO.File.Exists(txtCustomSound.Text))
                    {
                        ((App)Application.Current).HandleError("Custom Sound File Was Not Found", null, null, this, false);
                        return;
                    }
                }
                if (((TimerSound)ddlSoundEffect.SelectedValue) == TimerSound.TextToSpeech)
                {
                    if (string.IsNullOrEmpty(txtCustomSound.Text))
                    {
                        ((App)Application.Current).HandleError("Text for Text To Speech is required", null, null, this, false);
                        return;
                    }
                }
                TimerDefinition t = ((App)Application.Current).GetTimerDefinition((string)lstTimers.SelectedValue);
                if (t == null)
                {
                    ((App)Application.Current).HandleError("Timer Not Found", null, null, this, false);
                    lstTimers.ItemsSource = tdefs.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                    lstTimers.SelectedValue = null;
                    return;
                }
                bool wasEnabled = t.IsEnabled;
                t.IsEnabled = false;
                ((ParsecWindow)Owner).RemoveActiveTimer(t.Description);
                if (nameChanged)
                    t.Description = txtTimerName.Text;
                if ((TimerTrigger)ddlTrigger.SelectedValue == TimerTrigger.Custom)
                {
                    t.Trigger = TimerTrigger.Custom;
                    t.TriggerType = (TimerTriggerType)ddlTriggerType.SelectedValue;
                    t.CustomTriggerType = txtCustomType.Text;
                    t.TriggerTarget = (TimerTriggerTarget)ddlTriggerTarget.SelectedValue;
                    t.TriggerTargetName = (TimerTriggerTargetName)ddlTriggerTargetName.SelectedValue;
                    t.CustomTriggerTargetName = txtCustomTargetName.Text;
                }
                else
                {
                    t.SetTimerDefinitionBasedOnTrigger((TimerTrigger)ddlTrigger.SelectedValue);
                }
                if (t.TriggerType == TimerTriggerType.TimerExpires)
                {
                    t.CustomAbilityOrEffect = cmbTriggerTimerName.Text;
                }
                else
                {
                    t.CustomAbilityOrEffect = txtAbilityOrEffect.Text;
                }
                t.TimerInterval = interval;
                t.RepeatCount = repeatCount;
                t.MultiTimerMode = (MultipleTimerMode)ddlMultiTimerMode.SelectedValue;
                t.SoundEffect = (TimerSound)ddlSoundEffect.SelectedValue;
                t.CancelTimerName = cmbCancelTimerName.Text;
                t.Category = cmbCategory.Text;
                if (t.SoundEffect == TimerSound.Custom)
                    t.CustomSoundPath = txtCustomSound.Text;
                else
                    t.CustomSoundPath = null;
                if (t.SoundEffect == TimerSound.TextToSpeech)
                    t.TextToSpeechText = txtCustomSound.Text;
                else
                    t.TextToSpeechText = null;
                cmbCategory.ItemsSource = tdefs.Where(x => !string.IsNullOrEmpty(x.Category)).Select(x => x.Category).Distinct().OrderBy(x => x).Select(x => new ListBoxItem() { Content = x }).ToList();
                cmbCategory.SelectedValuePath = "Content";
                cmbCategory.DisplayMemberPath = "Content";
                cmbCategory.Text = t.Category;
                //if name is changed you must re bind list and reselect when finished
                if (nameChanged)
                {
                    string newName = txtTimerName.Text.Trim();
                    var timers = tdefs.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                    lstTimers.ItemsSource = timers;
                    lstTimers.SelectedValuePath = "Content";
                    lstTimers.SelectedValue = newName;
                    cmbTriggerTimerName.ItemsSource = timers;
                    cmbTriggerTimerName.SelectedValuePath = "Content";
                    cmbTriggerTimerName.DisplayMemberPath = "Content";
                    cmbCancelTimerName.ItemsSource = timers;
                    cmbCancelTimerName.SelectedValuePath = "Content";
                    cmbCancelTimerName.DisplayMemberPath = "Content";
                    BindTimerForm();
                }
                t.IsEnabled = wasEnabled;
                lblSaved.Content = string.Format("Saved @ {0}", DateTime.Now.ToShortDateString());
                lblUnsaved.Visibility = System.Windows.Visibility.Collapsed;
                lblSaved.Visibility = System.Windows.Visibility.Visible;
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnSaveTimer_Click", ex, this, true);
            }
        }
        private void btnDeleteTimer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (HandleMessage("Are you sure you want to delete this Timer?", true))
                {
                    lblUnsaved.Visibility = System.Windows.Visibility.Collapsed;
                    ((ParsecWindow)Owner).RemoveActiveTimer((string)lstTimers.SelectedValue);
                    ((App)Application.Current).RemoveTimerDefinition((string)lstTimers.SelectedValue);
                    var tdefs = ((App)Application.Current).GetTimerDefinitions();
                    var timers = tdefs.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                    lstTimers.ItemsSource = timers;
                    lstTimers.SelectedValuePath = "Content";
                    lstTimers.SelectedValue = null;
                    cmbCategory.ItemsSource = tdefs.Where(x => !string.IsNullOrEmpty(x.Category)).Select(x => x.Category).Distinct().OrderBy(x => x).Select(x => new ListBoxItem() { Content = x }).ToList();
                    cmbCategory.SelectedValuePath = "Content";
                    cmbCategory.DisplayMemberPath = "Content";
                    cmbTriggerTimerName.ItemsSource = timers;
                    cmbTriggerTimerName.SelectedValuePath = "Content";
                    cmbTriggerTimerName.DisplayMemberPath = "Content";
                    cmbCancelTimerName.ItemsSource = timers;
                    cmbCancelTimerName.SelectedValuePath = "Content";
                    cmbCancelTimerName.DisplayMemberPath = "Content";
                    BindTimerForm();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnDeleteTimer_Click", ex, this, true);
            }
        }
        private void btnDone_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                if (ConfirmUnsaved())
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnDone_Click", ex, this, true);
                this.Close();
            }
        }
        private void lstTimers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (grdFields.Visibility == System.Windows.Visibility.Visible && ((string)lstTimers.SelectedValue) == txtTimerName.Text)
                {
                    //do nothing;
                }
                else
                {
                    if (ConfirmUnsaved())
                    {
                        BindTimerForm();
                    }
                    else
                    {
                        if (e.RemovedItems.Count > 0)
                            lstTimers.SelectedItem = e.RemovedItems[0];
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on CreateGroupAdminPassOk", ex, this, true);
            }
        }
        public bool HandleMessage(string msg, bool showCancel)
        {
            if (!string.IsNullOrEmpty(msg))
            {
                MessageWindow m = new MessageWindow(msg, false, showCancel, true, true);
                m.Owner = this;
                return m.ShowDialog() ?? false;
            }
            return false;
        }
        public bool ConfirmUnsaved()
        {
            if (grdFields.Visibility == System.Windows.Visibility.Visible)
            {
                if (lblUnsaved.Visibility == System.Windows.Visibility.Visible)
                {
                    if (HandleMessage("You have unsaved changes. Continue?", true))
                    {
                        lblUnsaved.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            return true;
        }
        private void BindTimerForm()
        {
            if ((string)lstTimers.SelectedValue != null)
            {
                string timerName = (string)lstTimers.SelectedValue;
                TimerDefinition t = ((App)Application.Current).GetTimerDefinition(timerName);
                if (t != null)
                {
                    grdFields.Visibility = System.Windows.Visibility.Visible;
                    txtTimerName.Text = t.Description;
                    ddlTrigger.SelectedValue = (int)t.Trigger;
                    ddlTriggerType.SelectedValue = (int)t.TriggerType;
                    txtCustomType.Text = t.CustomTriggerType;
                    ddlTriggerTarget.SelectedValue = (int)t.TriggerTarget;
                    ddlTriggerTargetName.SelectedValue = (int)t.TriggerTargetName;
                    UpdateTriggerTargetNameFields();
                    txtCustomTargetName.Text = t.CustomTriggerTargetName;
                    if (t.TriggerType == TimerTriggerType.TimerExpires)
                    {
                        cmbTriggerTimerName.Text = t.CustomAbilityOrEffect;
                        txtAbilityOrEffect.Text = null;
                    }
                    else
                    {
                        cmbTriggerTimerName.Text = null;
                        txtAbilityOrEffect.Text = t.CustomAbilityOrEffect;
                    }
                    txtInterval.Text = t.TimerInterval.ToString();
                    txtRepeatCount.Text = t.RepeatCount.ToString();
                    ddlMultiTimerMode.SelectedValue = (int)t.MultiTimerMode;
                    ddlSoundEffect.SelectedValue = t.SoundEffect;
                    cmbCancelTimerName.Text = t.CancelTimerName;
                    cmbCategory.Text = t.Category;
                    if (t.SoundEffect == TimerSound.Custom)
                        txtCustomSound.Text = t.CustomSoundPath;
                    else if (t.SoundEffect == TimerSound.TextToSpeech)
                        txtCustomSound.Text = t.TextToSpeechText;
                    else
                        txtCustomSound.Text = null;
                    UpdateTriggerTypeFields();
                    UpdateTriggerFields();
                    UpdateSoundEffectFields();
                    lblSaved.Visibility = System.Windows.Visibility.Collapsed;
                    lblUnsaved.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    grdFields.Visibility = System.Windows.Visibility.Hidden;
                }
            }
            else
            {
                grdFields.Visibility = System.Windows.Visibility.Hidden;
            }
        }
        private void UpdateTriggerFields()
        {
            txtAbilityOrEffect.Visibility = System.Windows.Visibility.Visible;
            cmbTriggerTimerName.Visibility = System.Windows.Visibility.Collapsed;
            if (ddlTrigger.SelectedValue == null)
            {
                lblAbilityOrEffect.Content = "Ability";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.EnemyGainsAnEffect
                || (int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.EnemyLosesAnEffect
                || (int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.YouGainAnEffect
                || (int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.YouLoseAnEffect)
            {
                lblAbilityOrEffect.Content = "Effect";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.Custom)
            {
                lblAbilityOrEffect.Content = "Ability or Effect";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Visible;
            }
            else if ((int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.EventOccurs)
            {
                lblAbilityOrEffect.Content = "Event";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)(TimerTrigger)ddlTrigger.SelectedValue == (int)TimerTrigger.ATimerExpires)
            {
                lblAbilityOrEffect.Content = "Timer Name";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Collapsed;
                txtAbilityOrEffect.Visibility = System.Windows.Visibility.Collapsed;
                cmbTriggerTimerName.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                lblAbilityOrEffect.Content = "Ability";
                grdCustomTrigger.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void UpdateTriggerTypeFields()
        {
            txtAbilityOrEffect.Visibility = System.Windows.Visibility.Visible;
            cmbTriggerTimerName.Visibility = System.Windows.Visibility.Collapsed;
            if (ddlTriggerType.SelectedValue == null)
            {
                lblAbilityOrEffect.Content = "Ability";
                txtCustomType.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomType.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)ddlTriggerType.SelectedValue == (int)TimerTriggerType.EffectOff || (int)ddlTriggerType.SelectedValue == (int)TimerTriggerType.EffectOn)
            {
                lblAbilityOrEffect.Content = "Effect";
                txtCustomType.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomType.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)ddlTriggerType.SelectedValue == (int)TimerTriggerType.Custom)
            {
                lblAbilityOrEffect.Content = "Ability or Effect";
                txtCustomType.Visibility = System.Windows.Visibility.Visible;
                lblCustomType.Visibility = System.Windows.Visibility.Visible;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Visible;
            }
            else if ((int)ddlTriggerType.SelectedValue == (int)TimerTriggerType.EventOccurs)
            {
                lblAbilityOrEffect.Content = "Event";
                txtCustomType.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomType.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)ddlTriggerType.SelectedValue == (int)TimerTriggerType.TimerExpires)
            {
                lblAbilityOrEffect.Content = "Timer Name";
                txtCustomType.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomType.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Collapsed;
                txtAbilityOrEffect.Visibility = System.Windows.Visibility.Collapsed;
                cmbTriggerTimerName.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                lblAbilityOrEffect.Content = "Ability";
                txtCustomType.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomType.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTriggerTypeHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void UpdateTriggerTargetNameFields()
        {
            if (ddlTriggerTargetName.SelectedValue == null)
            {
                lblAbilityOrEffect.Content = "Ability";
                txtCustomTargetName.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomTargetName.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTargetNameHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if ((int)ddlTriggerTargetName.SelectedValue == (int)TimerTriggerTargetName.Custom)
            {
                txtCustomTargetName.Visibility = System.Windows.Visibility.Visible;
                lblCustomTargetName.Visibility = System.Windows.Visibility.Visible;
                btnCustomTargetNameHelp.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                txtCustomTargetName.Visibility = System.Windows.Visibility.Collapsed;
                lblCustomTargetName.Visibility = System.Windows.Visibility.Collapsed;
                btnCustomTargetNameHelp.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void UpdateSoundEffectFields()
        {
            if (ddlSoundEffect.SelectedValue == null)
            {
                txtCustomSound.Visibility = System.Windows.Visibility.Collapsed;
                btnBrowseSounds.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if (((TimerSound)ddlSoundEffect.SelectedValue) == TimerSound.Custom)
            {
                txtCustomSound.Visibility = System.Windows.Visibility.Visible;
                btnBrowseSounds.Visibility = System.Windows.Visibility.Visible;
            }
            else if (((TimerSound)ddlSoundEffect.SelectedValue) == TimerSound.TextToSpeech)
            {
                txtCustomSound.Visibility = System.Windows.Visibility.Visible;
                btnBrowseSounds.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                txtCustomSound.Visibility = System.Windows.Visibility.Collapsed;
                btnBrowseSounds.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void ddlTriggerType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lblUnsaved.Visibility = System.Windows.Visibility.Visible;
                UpdateTriggerTypeFields();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on ddlTriggerType_SelectionChanged", ex, this, true);
            }
        }
        private void ddlTriggerTargetName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lblUnsaved.Visibility = System.Windows.Visibility.Visible;
                UpdateTriggerTargetNameFields();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on ddlTriggerTargetName_SelectionChanged", ex, this, true);
            }
        }

        private void ddlTrigger_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lblUnsaved.Visibility = System.Windows.Visibility.Visible;
                UpdateTriggerFields();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on ddlTrigger_SelectionChanged", ex, this, true);
            }

        }
        private void ddlSoundEffect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                lblUnsaved.Visibility = System.Windows.Visibility.Visible;
                UpdateSoundEffectFields();
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on ddlTriggerType_SelectionChanged", ex, this, true);
            }
        }
        private void btnBrowseSounds_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Debug.WriteLine("Load Button Clicked");
                OpenFileDialog openFileDialog = new OpenFileDialog();
                if (string.IsNullOrEmpty(LastOpenedSoundFolder))
                {
                    string currentSoundFile = null;
                    if (!string.IsNullOrEmpty(txtCustomSound.Text))
                    {
                        try
                        {
                            currentSoundFile = System.IO.Path.GetDirectoryName(txtCustomSound.Text);
                        }
                        catch
                        {
                            currentSoundFile = null;
                        }
                    }
                    if (!string.IsNullOrEmpty(currentSoundFile) && System.IO.Directory.Exists(currentSoundFile))
                        openFileDialog.InitialDirectory = currentSoundFile;
                    else
                        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }
                else
                    openFileDialog.InitialDirectory = LastOpenedSoundFolder;
                openFileDialog.Filter = "Sound files (*.wav, *.mp3, *.mp4)|*.wav;*.mp3;*.mp4";
                bool? result = openFileDialog.ShowDialog();
                if (result.HasValue && result.Value)
                {
                    LastOpenedSoundFolder = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                    txtCustomSound.Text = openFileDialog.FileName;
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnBrowseSounds_Click", ex, this, true);
            }
        }
        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((TimerSound)ddlSoundEffect.SelectedValue != TimerSound.None)
                {
                    if ((TimerSound)ddlSoundEffect.SelectedValue == TimerSound.TextToSpeech)
                    {
                        if (!string.IsNullOrEmpty(txtCustomSound.Text))
                        {
                            ParsecClientHelpers.PlayTextToSpeech(txtCustomSound.Text);
                        }
                    }
                    else if ((TimerSound)ddlSoundEffect.SelectedValue == TimerSound.Custom)
                    {
                        if (!string.IsNullOrEmpty(txtCustomSound.Text) && System.IO.File.Exists(txtCustomSound.Text))
                        {
                            ParsecClientHelpers.PlayCustomSound(txtCustomSound.Text);
                        }
                    }
                    else
                    {
                        ParsecClientHelpers.PlaySound((TimerSound)ddlSoundEffect.SelectedValue);
                    }
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnPlay_Click", ex, this, true);
            }
        }

        private void btnCloneTimer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ConfirmUnsaved())
                {
                    string currentTimeName = (string)lstTimers.SelectedValue;
                    TimerDefinition toClone = ((App)Application.Current).GetTimerDefinition(currentTimeName);
                    if (toClone == null)
                        throw new Exception("Timer Definition Not Found");
                    int cloneCount = 1;
                    string cleanName = currentTimeName;
                    if (System.Text.RegularExpressions.Regex.IsMatch(cleanName, @"^\*.*\(\d+\)"))
                    {
                        cleanName = cleanName.Substring(1, (cleanName.LastIndexOf(" (") - 1));
                    }
                    string newTimerName;
                    var tdefs = ((App)Application.Current).GetTimerDefinitions();
                    do
                    {
                        newTimerName = string.Format("*{1} ({0})", cloneCount.ToString(), cleanName);
                        cloneCount++;
                    } while (tdefs.Count(x => string.Compare(x.Description, newTimerName, true) == 0) != 0);

                    TimerDefinition clone = toClone.Serialize().Deserialize<TimerDefinition>();
                    clone.Description = newTimerName;
                    ((App)Application.Current).AddTimerDefinition(clone);
                    tdefs = ((App)Application.Current).GetTimerDefinitions();
                    var timers = tdefs.OrderBy(x => x.Description).Select(x => new ListBoxItem() { Content = x.Description }).ToList();
                    lstTimers.ItemsSource = timers;
                    lstTimers.SelectedValuePath = "Content";
                    lstTimers.SelectedValue = newTimerName;
                    cmbTriggerTimerName.ItemsSource = timers;
                    cmbTriggerTimerName.SelectedValuePath = "Content";
                    cmbTriggerTimerName.DisplayMemberPath = "Content";
                    cmbCancelTimerName.ItemsSource = timers;
                    cmbCancelTimerName.SelectedValuePath = "Content";
                    cmbCancelTimerName.DisplayMemberPath = "Content";
                    BindTimerForm();
                    txtTimerName.Focus();
                    txtTimerName.SelectAll();
                }
            }
            catch (Exception ex)
            {
                ((App)Application.Current).HandleError("Error", "Error on btnCloneTimer_Click", ex, this, true);
            }
        }

        private void HelpButtonClick(object sender, RoutedEventArgs e)
        {
            Object pop = null;
            if (sender == this.lnkTimerOff)
                pop = this.popTimerOff;
            else if (sender == btnNameHelp)
                pop = popNameHelp;
            else if (sender == btnTriggerHelp)
                pop = popTriggerHelp;
            else if (sender == btnTriggerTypeHelp)
                pop = popTriggerTypeHelp;
            else if (sender == btnCustomTriggerTypeHelp)
                pop = popCustomTriggerTypeHelp;
            else if (sender == btnTriggerTargetHelp)
                pop = popTriggerTargetHelp;
            else if (sender == btnTargetNameHelp)
                pop = popTargetNameHelp;
            else if (sender == btnCustomTargetNameHelp)
                pop = popCustomTargetNameHelp;
            else if (sender == btnAbilityHelp)
                pop = popAbilityHelp;
            else if (sender == btnDurationHelp)
                pop = popDurationHelp;
            else if (sender == btnRepeatCountHelp)
                pop = popRepeatCountHelp;
            else if (sender == btnMultiTimerModeHelp)
                pop = popMultiTimerModeHelp;
            else if (sender == btnCancelOnTimerHelp)
                pop = popCancelOnTimer;
            else if (sender == btnCartegoryHelp)
                pop = popCategoryHelp;
            if (pop != null)
                ((System.Windows.Controls.Primitives.Popup)pop).IsOpen = true;
        }

        private void TextChangedHandler(object sender, TextChangedEventArgs e)
        {
            lblUnsaved.Visibility = System.Windows.Visibility.Visible;
        }

        private void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
        {
            lblUnsaved.Visibility = System.Windows.Visibility.Visible;
        }

    }
}
